<template>
  <div class="role">
    <page-search
      :search-config="searchConfig"
      @reset-query-list="resetQueryInfo"
      @user-query-list="userQueryList"
    />
    <page-content
      ref="pageContentRef"
      :content-config="contentConfig"
      @handler-new-click="handlerNewClick"
      @handler-edit-click="handlerEditClick"
    />
    <page-modal ref="pageModalRef" :modal-config="modalConfig" :introMenu="introMenu">
      <template #menuAssign>
        <el-tree
          :data="menuList"
          ref="treeRef"
          show-checkbox
          node-key="id"
          highlight-current
          :props="{ children: 'children', label: 'name' }"
          @check="handlerElTreeCheck"
        />
      </template>
    </page-modal>
  </div>
</template>

<script setup lang="ts">
import pageSearch from '@/components/page-search/page-search.vue'
import searchConfig from './config/searchConfig'

import pageContent from '@/components/page-content/page-content.vue'
import contentConfig from './config/contentConfig'

import pageModal from '@/components/page-modal/page-modal.vue'
import modalConfig from './config/modalConfig'

import usePageContent from '@/hooks/usePageContent'
import usePageModal from '@/hooks/usePageModal'
import useMainStore from '@/store/modules/main'
import { mapMenuIds } from '@/utils/map-menu'
import { storeToRefs } from 'pinia'
import { ref, nextTick } from 'vue'
import type { ElTree } from 'element-plus'

const introMenu = ref({})

const { pageContentRef, resetQueryInfo, userQueryList } = usePageContent()
const { pageModalRef, handlerNewClick, handlerEditClick } = usePageModal(
  newMenuState,
  editMenuState
)

// 展示角色管理中的菜单列表
const mainStore = useMainStore()
const { menuList } = storeToRefs(mainStore)
function handlerElTreeCheck(data1: any, data2: any) {
  const menuListArr = [...data2.checkedKeys, ...data2.halfCheckedKeys]
  introMenu.value = { menuList: menuListArr }
}
const treeRef = ref<InstanceType<typeof ElTree>>()
function newMenuState() {
  // 点击新建的时候让角色的权限重置
  nextTick(() => {
    treeRef.value?.setCheckedKeys([])
  })
}
function editMenuState(itemData: any) {
  // 点击编辑的时候让角色的权限回显
  nextTick(() => {
    const ids = mapMenuIds(itemData.menuList)
    treeRef.value?.setCheckedKeys(ids)
  })
}
</script>

<style lang="less" scoped></style>
